from flask import Blueprint, request, jsonify
from .models import KnowledgeItem  # 使用相对导入
from . import db  # 使用相对导入

knowledge_base_bp = Blueprint('knowledge_base', __name__)

@knowledge_base_bp.route('/knowledge-base', methods=['GET', 'POST'])
def knowledge_base():
    if request.method == 'POST':
        data = request.json
        title = data.get('title')
        content = data.get('content')

        if not title or not content:
            return jsonify({'error': '标题和内容不能为空'}), 400

        new_item = KnowledgeItem(title=title, content=content)
        db.session.add(new_item)
        db.session.commit()

        return jsonify({'message': '知识库条目已添加'}), 201

    search = request.args.get('search')
    if search:
        items = KnowledgeItem.query.filter(
            KnowledgeItem.title.contains(search) | KnowledgeItem.content.contains(search)).all()
    else:
        items = KnowledgeItem.query.all()

    items_data = [{'id': item.id, 'title': item.title, 'content': item.content} for item in items]
    return jsonify(items_data), 200

